import 'dart:core';

import 'package:flutter/material.dart';
import 'package:flutter_speed_dial/flutter_speed_dial.dart';

import '../common/flatPanel.dart';
import '../utils/dataSource.dart';
import '../utils/screw.dart';

mixin TraitSearchController {
  final mDb = DataSource();
  final mCats = <String>[];
  final mLabels = <String>[];
  final mCache = Map<String, String>();
  final pCat = 'Default', pLabel = '[百度搜索]';

  String mTable;
  var mViewState = ViewState.Initial;
  String mCat;
  String mLabel;

  disposeAction() {
    mCats.clear();
    mLabels.clear();
    mCache.clear();
    mDb.close();
  }

  void onConnectDb();

  Future<void> connectDbAction(
      BuildContext context, String entry, Function function) async {
    bool result = await mDb.connectFromHive(entry);
    if (result) {
      await updateCacheAction();
      function();
    } else {
      Screw.showToast(context, '无法连接到数据库!');
    }
  }

  void onUpdateTopics();

  Future<void> updateTopicsAction() async {
    if (mCats.isNotEmpty) {
      mCats.clear();
    }

    if (mDb.isConnect) {
      var results =
          await mDb.query('select category from $mTable group by category');
      results.forEach((element) {
        mCats.add(element[0] ?? '');
      });
    }

    if (mCats.isEmpty) {
      mCat = pCat;
      mCats.add(pCat);
    }
  }

  void onUpdateLabels();

  Future<void> updateLabelsAction() async {
    if (mLabels.isNotEmpty) {
      mLabels.clear();
    }

    if (mDb.isConnect) {
      var results =
          await mDb.query('select label from $mTable where category=?', [mCat]);
      results.forEach((element) {
        mLabels.add(element[0] ?? '');
      });
    }

    if (mLabels.isEmpty) {
      mLabels.add(pLabel);
    }
  }

  Future<void> updateCacheAction() async {
    if (mCache.isNotEmpty) mCache.clear();

    if (mDb.isConnect) {
      var results = await mDb.query('select label,detail from $mTable');
      results.forEach((element) {
        mCache[element[0]] = element[1];
      });
    }
  }

  Widget genSpeedDialAction() {
    return SpeedDial(
      child: Icon(Icons.list),
      children: genSpeedDialChildAction(),
    );
  }

  List<SpeedDialChild> genSpeedDialChildAction() {
    var speedDials = <SpeedDialChild>[];
    speedDials = mCats
        .map((e) => SpeedDialChild(
              child: Icon(Icons.title),
              backgroundColor: Screw.getRandomColor(),
              label: e,
              onTap: () {
                mCat = e;
                onUpdateLabels();
              },
            ))
        .toList();
    return speedDials;
  }
}
